<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Version;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;

class PayController extends Controller
{
    private $wx_config;
    private $alipay;
    private $user_id;
    public function __construct()
    {
        $this->user_id = Auth::id();
        $this->wx_config = Config::get('pay.wechat');
        $this->alipay = Config::get('pay.alipay');
    }
    //生成订单
    public function index(Request $request)
    {
        $id = $request->input('id');
        $num = $request->input('num');
        $payType = $request->input('payType');
        if (!in_array($payType, [1, 2]) && !in_array($num, [1, 2, 3, 4])) {
            return $this->respond('empty_error');
        }
        $term = $request->input('term');
        $price = $request->input('price');
        if (empty($id) || empty($term) || empty($price) || empty($num)) {
            return $this->respond('empty_error');
        }
        $item = Version::find($id);
        if (empty($item)) {
            return $this->respond('get_error');
        }
        if ($num == 1) {
            $discount = $item->discount1;
            if ($item->term1 != $term || $item->price1 != $price) {
                return $this->respond('empty_error');
            }
        } else if ($num == 2) {
            $discount = $item->discount2;
            if ($item->term2 != $term || $item->price2 != $price) {
                return $this->respond('empty_error');
            }
        } else if ($num == 3) {
            $discount = $item->discount3;
            if ($item->term3 != $term || $item->price3 != $price) {
                return $this->respond('empty_error');
            }
        } else if ($num == 4) {
            $discount = $item->discount4;
            if ($item->term4 != $term || $item->price4 != $price) {
                return $this->respond('empty_error');
            }
        }
        $order_no = date('YmdHis') . mt_rand(100000, 999999);
        //微信支付
        if ($payType == 1) {
            $order = [
                'out_trade_no' => $order_no,
                'total_amount' => '1',
                'subject' => $item->name,
            ];
            try {
                $pay = Pay::wechat($this->wx_config);
                $result = $pay->web($order)->send();
            } catch (Exception $e) {
                $e->getMessage();
            }
        } else if ($payType == 2) {
            //支付宝支付
            try {
                $order = [
                    'out_trade_no' => $order_no,
                    'total_amount' => $price,
                    'subject' => $item->name,
                ];
                $order_data = [
                    'userId' => $this->user_id,
                    'versionId' => $item->id,
                    'name' => $item->name,
                    'orderNo' => $order_no,
                    'term' => $term,
                    'price' => $price,
                    'type' => $payType,
                    'discount' => $discount,
                ];
                Order::create($order_data);
                $result = Pay::alipay($this->alipay)->web($order);
                return response($result);

            } catch (GatewayException $e) {
                \log::info('支付调起失败:', $e->getMessage());
            }
        }
    }
    //去支付
    public function gopay(Request $request)
    {
        $id = $request->input('id');
        $payType = $request->input('payType');
        if (!in_array($payType, [1, 2])) {
            return $this->respond('empty_error');
        }
        $item = Order::find($id);
        if (empty($item)) {
            return $this->respond('get_error');
        }
        //微信支付
        if ($payType == 1) {
            $order = [
                'out_trade_no' => $item->orderNo,
                'total_amount' => '1',
                'subject' => $item->name,
            ];
            try {
                $pay = Pay::wechat($this->wx_config);
                $result = $pay->web($order)->send();
            } catch (Exception $e) {
                $e->getMessage();
            }
        } else if ($payType == 2) {
            //支付宝支付
            try {
                $order = [
                    'out_trade_no' => $item->orderNo,
                    'total_amount' => $item->price,
                    'subject' => $item->name,
                ];
                $item->timestamps = false;
                $item->type = $payType;
                $item->save();
                $result = Pay::alipay($this->alipay)->web($order);
                return response($result);

            } catch (GatewayException $e) {
                \log::info('支付调起失败:', $e->getMessage());
            }
        }
    }

    public function notifyUrl()
    {
        \log::info('支付异步回调开始:', ['date' => date('Y-m-d H:i:s')]);
        $alipay = Pay::alipay($this->alipay);

        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！
            Log::debug('Alipay notify', $data->all());
            if ($data->trade_status == 'TRADE_SUCCESS' || $data->trade_status == 'TRADE_FINISHED') {
                if ($data->seller_id == env('APIPAY_PID')) {
                    $order_no = $data->out_trade_no;
                    $order = Order::where('orderNo', $order_no)->first();
                    if (!empty($order)) {
                        if ($order->term == '1年') {
                            $order->validity = strtotime('+1 year');
                        } else if ($order->term == '2年') {
                            $order->validity = strtotime('+2 year');
                        } else if ($order->term == '4年') {
                            $order->validity = strtotime('+4 year');
                        }
                        $order->status = 2;
                        $order->outTradeNo = $data->trade_no;
                        $re = $order->save();
                        return $alipay->success();
                    }
                }
            }
            \log::info("支付回调成功", ['out_trade_no' => $data->out_trade_no, 'trade_status' => $data->trade_status]);
        } catch (Exception $e) {
            $e->getMessage();
        }
        \log::info('支付异步回调结束:', ['date' => date('Y-m-d H:i:s')]);
    }
    public function returnUrl()
    {
        \log::info('支付同步回调成功:', ['date' => date('Y-m-d H:i:s')]);
        dd('支付同步回调成功 date:' . date('Y-m-d H:i:s'));
    }
}
